import os
import subprocess

from setuptools import find_packages, setup
from torch.utils.cpp_extension import BuildExtension, CUDAExtension

def get_git_commit_number():
    if not os.path.exists('.git'):
        return '0000000'

    cmd_out = subprocess.run(['git', 'rev-parse', 'HEAD'], stdout=subprocess.PIPE)
    git_commit_number = cmd_out.stdout.decode('utf-8')[:7]
    return git_commit_number


def make_cuda_ext(name, module, sources):
    cuda_ext = CUDAExtension(
        name='%s.%s' % (module, name),
        sources=[os.path.join(*module.split('.'), src) for src in sources]
    )
    return cuda_ext


def write_version_to_file(version, target_file):
    with open(target_file, 'w') as f:
        print('__version__ = "%s"' % version, file=f)


if __name__ == '__main__':
    version = '0.0.1+%s' % get_git_commit_number()
    setup(
        name='dsvt',
        version=version,
        description='dsvt is a private codebase for Dynamtic Windows Partition',
        install_requires=[
            'nibabel',
            'tqdm',
            'einops',
            'tensorboardX',
            'monai @ git+https://github.com/Project-MONAI/MONAI.git@07de215c'
        ],

        author='Haojiang Ye',
        author_email='yhjiang0114@163.com',
        license='Apache License 2.0',
        packages=find_packages(exclude=['assets','utils', 'data', 'outputs', 'json']),
        cmdclass={
            'build_ext': BuildExtension,
        },
        ext_modules=[
            make_cuda_ext(
                name='ingroup_inds_cuda',
                module='dsvt.ingroup_inds',
                sources=[
                    'src/ingroup_inds.cpp',
                    'src/ingroup_inds_kernel.cu',
                ]
            ),
        ],
    )
